const express = require('express')
const router = express.Router()
const { goods } = require('../db')


router.get('/',async (req, res)=>{
    try {
        const data = await goods.find({},{"__v":0})
        res.json(data)
    } catch (error) {
        res.json({code:0, msg:'notfind'})
    }
})

router.post('/add', async (req, res)=>{
    try {
        const {title, data} = req.body
        const goodsItem = await goods.find({title})
        goodsItem[0].data.unshift(data)
        await goods.updateMany({title}, goodsItem[0])
        res.json({code:1, msg: 'add ok'})
    } catch (error) {
        console.log(error);
        res.json({code:0, msg: 'add err'})
    }   
})

router.post('/update', async (req, res)=>{
    try {
        const { id, data } = req.body
        const [item] = await goods.find({data: {$elemMatch: {_id:id}}})
        const newItem = JSON.parse(JSON.stringify(item))
        newItem.data = newItem.data.map(item=>{
            if(item._id == id) item = {...item, ...data}
            return item
        })
        await goods.updateMany(item, newItem)
        res.json({code:1, msg: 'update ok'})
    } catch (err) {
        res.json({code: 0, msg: `data is null`})
    }   
})


router.get('/del', async (req, res)=>{
    const {id} = req.query
    try {
        const [item] = await goods.find({data: {$elemMatch: {_id:id}}})
        const newItem = JSON.parse(JSON.stringify(item))
        newItem.data = newItem.data.filter(item=>!(item._id == id))
        await goods.updateMany(item, newItem)
        res.json({code:500, msg: 'delete ok'})
    } catch (err) {
        res.json({code: 502, msg: `${id} is null`})
    }   
})


module.exports = router